package com.test.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 面试题：按照顺序指向三个线程，A B C
 * A 输出1遍字符AA
 * B 输出2遍字符BB
 * C 输出3遍字符CC
 * <p>
 * 执行十轮
 * <p>
 * <p>
 * countDownLatch的使用
 *
 * 错误，这里并不能保证 线程ABC的顺序，只能保证 主线程在 ABC后执行
 */
public class BaguwenThread2 {

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 10; i++) {


            CountDownLatch lock = new CountDownLatch(3);

            // 提交任务1
            executorService.execute(() -> {
                try {
                    System.out.println("AA");
                } finally {
                    lock.countDown();
                }
            });

            // 提交任务2
            executorService.execute(() -> {
                try {
                    System.out.println("BB");
                    System.out.println("BB");
                } finally {
                    lock.countDown();
                }
            });

            // 提交任务3
            executorService.execute(() -> {
                try {
                    System.out.println("CC");
                    System.out.println("CC");
                    System.out.println("CC");
                } finally {
                    lock.countDown();
                }
            });

            // 释放主线程，主线程继续往下执行
            lock.await();


        }
    }
}
